package com.kitty.syn;
//生产者、消费者。
class Go{
	public static final int MAX_NUM=100;//最大库存量
	private int currennum;//当前库存
	Go(){}
	Go(int currennum){
		this.currennum=currennum;
	}
	public synchronized void produce(int neednum){
		System.out.println("要生产的产品数量"+neednum+"与现有仓储靓之和大于最大仓储量"+MAX_NUM+"，所以不能生产！！");
		while(currennum+neednum>MAX_NUM){
			try {
				this.wait();//使当前线程阻塞，并释放锁
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		currennum+=neednum;
		System.out.println("已经生产了"+neednum+",现在仓储量为："+currennum);
		this.notifyAll();//不释放锁，也不获得锁，仅通知其他线程可以竞争执行
	}
	public synchronized void consum(int neednum){
		while(currennum<neednum){
			System.out.println("现有仓储量不足，无法消费！！");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		currennum-=neednum;
		System.out.println("已经消费了"+neednum+",现在仓储量为："+currennum);
		this.notifyAll();
	}
}
class Producer extends Thread{
	private int neednum;
	private Go go;
	Producer(int neednum,Go go){
		this.neednum=neednum;
		this.go=go;
	}
	public void run(){
		go.produce(neednum);
	}
}
class Consumer extends Thread{
	private int neednum;
	private Go go;
	Consumer(int neednum,Go go){
		this.neednum=neednum;
		this.go=go;
	}
	public void run(){
		go.consum(neednum);
	}
}
public class Practice extends Thread{
	public static void main(String[] args){
		Go go=new Go(30);
		new Consumer(50,go).start();
		new Consumer(20,go).start();
		new Consumer(30,go).start();
		new Producer(10,go).start();
		new Producer(10,go).start();
		new Producer(10,go).start();
		new Producer(10,go).start();
		new Producer(10,go).start();
		new Producer(80,go).start();
}
}
